from django.db.models import Q
from django.shortcuts import render
from utils.group import NbSearchGroup, Option
from utils.pager import Pagination
from web.models import TransactionRecord


def my_transaction_list(request):
    # 筛选框
    # 第一步：配置和传参
    search_group = NbSearchGroup(
        request,
        TransactionRecord,
        Option('charge_type', is_multi=True),  # choices类型
    )
    # 加上搜索框关键字条件
    keyword = request.GET.get('keyword', '').strip()
    con = Q()
    if keyword:
        con.connector = 'OR'
        con.children.append(('order_oid__contains', keyword))

    queryset = (TransactionRecord.objects.filter(con)
                .filter(**search_group.get_condition)  # 第二步：获取选中筛选条件
                .filter(customer_id=request.my_user.id, customer__active=True).order_by('-id'))

    pager = Pagination(request, queryset, per_page_count=5)

    context = {
        'pager': pager,
        'keyword': keyword,
        'search_group': search_group,  # 第三步：传入前端页面
    }
    return render(request, 'my_transaction_list.html', context)


def transaction_list(request):
    # 筛选框
    # 第一步：配置和传参
    search_group = NbSearchGroup(
        request,
        TransactionRecord,
        Option('charge_type', is_multi=True),  # choices 类型
    )
    # 加上搜索框关键字条件
    keyword = request.GET.get('keyword', '').strip()
    con = Q()
    if keyword:
        con.connector = 'OR'
        con.children.append(('order_oid__contains', keyword))
        con.children.append(('customer__username__contains', keyword))

    queryset = (TransactionRecord.objects.filter(con)
                .filter(**search_group.get_condition)  # 第二步：获取选中筛选条件
                .filter(customer__active=True).select_related('customer').order_by('-id'))

    pager = Pagination(request, queryset, per_page_count=5)

    context = {
        'pager': pager,
        'keyword': keyword,
        'search_group': search_group,  # 第三步：传入前端页面
    }
    return render(request, 'transaction_list.html', context)
